﻿using Approval.API.Applcation.Command.HCTRelationCommand;
using Approval.Domain;
using Approval.Infrastructure.Impl;
using Approval.Infrastructure.Interface;
using MediatR;

namespace Approval.API.Applcation.CommandHandler.HCTRelationCommandHandler
{
    public class HCTRelationCreateCommandHandler : IRequestHandler<HCTRelationCreateCommand, int>
    {
        private readonly IHCTRelationRepository hCTRelationRepository;

        public HCTRelationCreateCommandHandler(IHCTRelationRepository hCTRelationRepository)
        {
            this.hCTRelationRepository = hCTRelationRepository;
        }

        public async Task<int> Handle(HCTRelationCreateCommand request, CancellationToken cancellationToken)
        {
            var list = await hCTRelationRepository.GetInfo(x => x.HCTId == request.HctId && x.ApprovalState == 3);
            if (list != null)
            {
                await hCTRelationRepository.Delete(list.Id);
            }
            //默认第一次提交付款审批是彭于晏
            var hctRelation = new HCTRelation()
            {
                HCTId = request.HctId,
                ApprovalId = request.ApprovalId != 0 ? request.ApprovalId : 4,
                ApprovalName = (request.ApprovalName == "") ? request.ApprovalName : "彭于晏",
                ApprovalDesc = null
            };
            var res = await hCTRelationRepository.Create(hctRelation);
            return res;
        }
    }
}
